package com.zbkj.service.manager.impl;

import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.common.utils.MoneyUtil;
import com.zbkj.dal.dao.ProductDao;
import com.zbkj.dal.entity.product.Product;
import com.zbkj.dal.entity.user.UserQuotaAccount;
import com.zbkj.service.manager.FundManager;
import com.zbkj.service.manager.OrderManager;
import com.zbkj.service.manager.QuotaManager;
import com.zbkj.service.model.dto.OrderPreCheckDTO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

@Component
public class OrderManagerImpl implements OrderManager {

    @Resource
    private ProductDao productDao;

    @Resource
    private FundManager fundManager;

    @Resource
    private QuotaManager quotaManager;

    @Override
    public OrderPreCheckDTO orderPreCheck(Integer userId, Integer productId) {
        UserQuotaAccount userQuotaAccount = quotaManager.userQuotaAccount(userId);

        Product product = productDao.selectById(productId);
        if (Objects.isNull(product)) {
            throw new CrmebException("商品不存在");
        }
        BigDecimal price = product.getPrice();

        BigDecimal quotaBalance = userQuotaAccount.getQuotaBalance();

        OrderPreCheckDTO orderPreCheckDTO = new OrderPreCheckDTO();
        orderPreCheckDTO.setEnough(price.compareTo(quotaBalance) < 0);
        orderPreCheckDTO.setQuota(MoneyUtil.prettyFormat(price));
        BigDecimal needQuota = price.compareTo(quotaBalance) < 0 ? BigDecimal.ZERO : price.subtract(quotaBalance);
        orderPreCheckDTO.setNeedQuota(MoneyUtil.prettyFormat(needQuota));

        return orderPreCheckDTO;
    }
}
